package com.mina;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.concurrent.CompletableFuture;


/**
 * @author MH
 */
public class ClientTest {
    private final Socket socket;

    public static void main(String[] args) {
        try {
            ClientTest test = new ClientTest();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ClientTest() throws Exception {
        socket = new Socket("localhost", 80);
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());

        waitClientInput();

        int count = 0;
        byte[] buffer = new byte[1024];

        while (true) {
            count = bis.read(buffer);
            if (count == -1) {
                break;
            }

            System.out.print("服务器说:" + new String(buffer, 0, count, "UTF-8"));
        }

        bis.close();
        socket.close();
    }

    private void waitClientInput() {
        CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                BufferedWriter bw = null;
                try {
                    bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                String s = null;
                while (true) {
                    try {
                        s = br.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    if (s.equals("bye")) {
                        try {
                            bw.write(s);
                            bw.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        break;
                    }

                    try {
                        // 注意！此处如果不主动为输入的字符串加入\n换行符，则MINA服务器端收不到。
                        s = s + "\n";

                        bw.write(s);
                        bw.flush();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                try {
                    br.close();
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}